package edu.tamu.cse.lenss.sensor;

import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;

public class WiFiController {
	private WifiManager mainWifi;
	private WifiReceiver wifiReceiver;
	private Context context;
	private WifiControllerListener listener;
	
	public WiFiController(Context context, WifiControllerListener lis){
		this.context = context;
		this.listener = lis;
		this.mainWifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
	}
	
	public void startScan(){
		IntentFilter filter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
		//filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
		wifiReceiver = new WifiReceiver();
		// Turn on Wifi
		if(mainWifi.setWifiEnabled(true)){
			context.registerReceiver(wifiReceiver, filter);
			mainWifi.startScan();
		}
	}
	
	public void stopScan(){
		context.unregisterReceiver(wifiReceiver);
	}

	/*
	 * Helper Inner class
	 */
	class WifiReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context arg0, Intent arg1) {
			List<ScanResult> wifiList = mainWifi.getScanResults();
			listener.onStateChanged(wifiList);
		}
	}
	
	public static interface WifiControllerListener{
		public void onStateChanged(List<ScanResult> results);
	}
}
